/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL) {
            return vector<vector<int> >();
        }
        vector<vector<int> > ans;
        vector<int> q;
        dfs(root, 0, sum, q, ans);
        return ans;
    }

    void dfs(TreeNode *root, int curSum, int target, vector<int> &q, vector<vector<int> > &ans) {
        if (!root->left && !root->right) {
            q.push_back(root->val);
            if (curSum + root->val == target) {
                ans.push_back(q);
            }
            q.pop_back();
            return;
        }
        q.push_back(root->val);
        if (root->left) {
            dfs(root->left, curSum + root->val, target, q, ans);
        }

        if (root->right) {
            dfs(root->right, curSum + root->val, target, q, ans);
        }
        q.pop_back();
    }
};
